/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 言初
 * Date: 2024-05-25
 * Time: 22:38
 */
public class Test1 {

    int countreaders;//当前有多少进程正在读
    boolean read;
    boolean write;
    // 现在能不能读，现在能不能写（值为true，就表示现在能做某事； 值为false，就表示现在不能做某事）

    public Test1(){
        countreaders = 0;
        read = true;
        write = true;
    }

    //读操作
    public synchronized void read(String name){
        while(read==false){
            try {
                System.out.println(name+" is waiting");
                // 等待notify发出
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(name+"开始读");
        write=false;
        read=true;
        countreaders++;

    }
    //结束读操作
    public synchronized void endread(String name){
        countreaders--;
        if(countreaders==0){
            write=true;
        }
        notifyAll();
        System.out.println(name+"读结束");
    }

    // 写操作
    public synchronized void write(String name){
        while(write==false){
            try {
                System.out.println(name+" is waiting");
                // 等待notify发出
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name+"正在写");
        read=false;
        write=false;
    }
    // 结束写操作
    public synchronized void endwrite(String name){
        read=true;
        write=true;
        notifyAll();
        System.out.println(name+"结束写");
    }
}
